using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Player : MonoBehaviour
{
    public float runSpeed = 8f;
    public float attackRadius = 1f;
    public Transform attackPoint;
    public Slider healthSlider;

    private float Health=100f;
    private bool damageMade;
    private CharacterController player_controller;
    private Animator player_animator;
    

    private void Awake()
    {
        player_animator = GetComponent<Animator>();
        player_controller = GetComponent<CharacterController>();
        healthSlider.value = Health*0.01f;
    }
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        
        player_controller.checkGround();
        float movedirection = Input.GetAxis("Horizontal");
        if (player_controller.isGrounded())
        {
            if (movedirection == 0f)
            {
                player_animator.SetBool("IsWalk", false);
            }
            else
            {
                player_animator.SetBool("IsWalk", true);
            }
        }

        if (movedirection > 0)
        {
            if (transform.localScale.x < 0f)

                transform.localScale = new Vector3(-transform.localScale.x, transform.localScale.y, transform.localScale.z);
        }
        else if (movedirection < 0)
        {
            if (transform.localScale.x > 0f)

                transform.localScale = new Vector3(-transform.localScale.x, transform.localScale.y, transform.localScale.z);
        }


        if (player_controller.isGrounded() && Input.GetKeyDown(KeyCode.Space))
        {
            player_controller.jump();
            player_animator.SetTrigger("Jump");

        }

        if (player_controller.isGrounded() && Input.GetKeyDown(KeyCode.J))
        {
            player_animator.SetTrigger("Attack");

        }
        if (attackPoint.gameObject.activeSelf == true && damageMade == false)
        {
            damageMade = true;
            Collider2D[] hittedObjects = Physics2D.OverlapCircleAll(attackPoint.position, attackRadius);
            if (hittedObjects.Length > 0)
            {
                for (int i = 0; i < hittedObjects.Length; i++)
                {
                    if (hittedObjects[i].gameObject != gameObject)
                    {
                        Npc enemy = hittedObjects[i].gameObject.GetComponent<Npc>();
                        if (enemy != null)
                        {
                            enemy.Hurt(20);
                        }
                    }
                }
            }
        }
        else if (attackPoint.gameObject.activeSelf == false && damageMade == true)
        {
            damageMade = false;
        }

        player_controller.Move(movedirection * new Vector3(runSpeed, 0f, 0f));
    }


}
